<template>
    <div class="my-header">
        <el-tabs v-model="data.activeName" class="demo-tabs">
            <el-tab-pane label="创新平台建设奖" name="first">
                <el-form :rules="rules" ref="ruleFormRef" :model="ruleForm" label-width="120px" class="demo-ruleForm"
                    status-icon>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="平台名称" prop="name">
                                <el-input placeholder="" v-model="ruleForm.name" style="width: 150px" :disabled="1"  />
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="获批时间" prop="approvedDate">
                                <el-date-picker v-model="ruleForm.approvedDate" type="date" placeholder="获批时间"
                                    format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                                    style="width: 150px; margin-right: 15px" :disabled="1" ></el-date-picker>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="资金补助(万元)" prop="subsidy">
                                <el-input type="number" :min="0" v-model="ruleForm.subsidy" style="width: 150px"  :disabled="1" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="平台级别" prop="level">
                                <SelectOption :selectValue="ruleForm.level" :options="options.levelOptions"
                                    @change-value="changeValue" :disabled="1" > </SelectOption>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="平台类别" prop="subject">
                                <SelectOption :selectValue="ruleForm.subject" :options="options.xtcxTypeSelect"
                                    @change-value="changeValue1" :disabled="1" > </SelectOption>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="获批文件编号" prop="approvedNumber">
                                <el-input placeholder="" v-model="ruleForm.approvedNumber" style="width: 150px"  :disabled="1" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <!-- <el-col :span="8">
                            <el-form-item label="奖励标准" prop="incentivestandard">
                                <SelectOption :selectValue="ruleForm.incentivestandard" :options="options.jlbzList"
                                @change-value="changeValue3"> </SelectOption>
                            </el-form-item>
                        </el-col> -->
                    </el-row>
                    <el-row>
                        <el-col :span="16">
                            <el-form-item label="主建单位">
                                <el-cascader :disabled="data.lobarDisabled" :options="data.selOp" :props="data.props" popper-class="gy-cascader"
                                    style="width: 100%;" filterable="" ref="cascader1" v-model="data.mainValue" @change="chooseMatter"
                                    placeholder="请选择" :show-all-levels="false"  >
                                        <template #default="{ data }">
                                        <el-tooltip
                                        :disabled="data.name.length < 13"
                                            class="item"
                                            effect="dark"
                                            :content="data.name"
                                            placement="bottom-start"
                                        >
                                            <span>{{ data.name }}</span>
                                        </el-tooltip>
                                        </template>
                                </el-cascader>
                            </el-form-item>
                        </el-col>
                        <el-col :span="16">
                            <el-form-item label="共建单位">
                                <el-cascader :disabled="data.lobarDisabled" :options="data.selOp" :props="data.props" popper-class="gy-cascader"
                                    clearable="" style="width: 100%;" filterable="" @change="chooseMatter1" ref="cascader1"
                                    v-model="data.mainValue1" placeholder="请选择"
                                    :show-all-levels="false" >
                                    <template #default="{ data }">
                                    <el-tooltip
                                    :disabled="data.name.length < 13"
                                        class="item"
                                        effect="dark"
                                        :content="data.name"
                                        placement="bottom-start"
                                    >
                                        <span>{{ data.name }}</span>
                                    </el-tooltip>
                                    </template>
                                </el-cascader>
                                <!-- @remove-tag="removeTag1" -->
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="建设情况简介" prop="introduction">
                                <el-input v-model="ruleForm.introduction" :autosize="{ minRows: 3 }" maxlength="1000"
                                    type="textarea"  :disabled="1" />
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </el-tab-pane>
        </el-tabs>

    </div>
</template>

<script lang="ts">
import * as proxy from "@/constants/proxy"
import request from "@/utils/request"
import SelectOption from '@/views/science/components/selectOption/index.vue'
import { tips } from '@/views/science/components/tips/tips'
import { computed, nextTick, onMounted, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'
export default {
    components: {
        SelectOption,
    },
    emits: {
        usersChange: null,
        paramsChange: null,
        valueFlag2:null,
    },
    props: {
        fbData: {
            type: Object,
            required: true,
        },
        users: {
            type: Array,
            required: true,
        },
        addFlag: {
            type: Number,
            required: true,
        }
    },
    setup(props, { emit }) {
        const store = useStore()
        const labelPosition = ref('right')
        const data = reactive({
            activeName: ref('first'),
            dialogVisible: false,
            lobarDisabled: false,
            props: {
                checkStrictly : true,
                multiple: true,
                expandTrigger: 'hover',
                value: 'id',
                label: 'name',
                children: 'children',
                emitPath: false
            },
            mainValue: [] as any,
            mainValue1: [] as any,
            chooseMatterList: [],

            page: { page: 1, limit: 10, total: 0 },
            ids: [],
            params: {
                current: 1,
                id: "",
                name: "",
                size: 10
            },
            allTableData: [],
            columns: [
                {
                    key: 'joinusername',
                    width: 140,
                    label: '姓名',
                },
                {
                    key: 'unit',
                    width: 140,
                    label: '单位',
                },
                {
                    key: 'role',
                    width: 140,
                    label: '担任角色',
                }
            ],
            selOp:[] as any,
        })

        // 弹窗中三个下拉选择
        let options = reactive({
            levelOptions: computed(() => store.state.technologyStrength.levelSelect),
            xtcxTypeSelect: computed(() => store.state.technologyStrength.xtcxTypeSelect),
            jlbzList: [
                {
                    id: '1',
                    itemText: '技术创新与成果转化类20万',
                    itemValue: 20
                },
                {
                    id: '2',
                    itemText: '基础支撑与件保障类20万',
                    itemValue: 20
                },
                {
                    id: '3',
                    itemText: '国家认定企业技术中心20万',
                    itemValue: 20
                },
                {
                    id: '4',
                    itemText: '国家技术标准创新基地20万',
                    itemValue: 20
                },
                {
                    id: '5',
                    itemText: '重点实验室5万',
                    itemValue: 5
                },
                {
                    id: '6',
                    itemText: '研发中心5万',
                    itemValue: 5
                }
            ],
        })
        const getOrgList = () =>{
            return request({
                url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
                method: "get",
            }).then(res =>{
                data.selOp = res.data.data
            })
        }

        const innovate = ref(props.fbData)

        const usersList = ref(props.users)

        const ruleForm = reactive({
            id:'',
            awardApplyId: '',
            name: '',
            approvedDate: '',
            subsidy: '',
            level: '',
            levelId: '',
            subject: '',
            subjectId: '',
            approvedNumber: '',
            mainUnitName: '',
            mainUnitId: '',
            constructionUnitName: '',
            constructionUnitId: '',
            introduction: '',
            incentivestandard:'',
            incentivestandardid: "",
        },)

        const handleData = (data) => {
            const arr1 = Object.keys(data)
            const list = ruleForm
            for (const key in list) {
                if (arr1.indexOf(key) !== -1) {
                    list[key] = data[key]
                }
            }
            return list
        }

        const mainValue: any = ref([])
        const mainValue1: any = ref([])

        watch(props, (newValue, oldValue) => {
            console.log('watchwatch',newValue)
            innovate.value = newValue.fbData
            usersList.value = newValue.users
            Object.assign(ruleForm, handleData(newValue.fbData || {}))
            // mainValue.value = ruleForm.mainUnitId.split(',')
            // mainValue1.value = ruleForm.constructionUnitId.split(',')
            // data.mainValue = ruleForm.mainUnitId.split(',')
            // data.mainValue1 = ruleForm.constructionUnitId.split(',')
        },{deep:true});

        watch(
            () => props.addFlag,
            (newVal, oldVal) => {
                // Object.keys(ruleForm).forEach((key) => {
                //     ruleForm[key] = ''
                // })
                data.mainValue = ruleForm.mainUnitId.split(',')
                data.mainValue1 = ruleForm.constructionUnitId.split(',')
            }
        )

        // 提交表单-字段对照新增接口-然后同步
        // const ruleForm = reactive(store.state.technologyStrength.fbxxINFO)
        watch(ruleForm, (newValue, oldValue) => {
            emit('paramsChange', newValue)
        });

        const changeValue = (item) => {
            ruleForm.level = item.itemText
            ruleForm.levelId = item.itemValue
        }
        const changeValue1 = (item) => {
            ruleForm.subject = item.itemText
            ruleForm.subjectId = item.itemValue
        }

        const changeValue3 = (item) => {
            ruleForm.incentivestandard = item.itemText
            ruleForm.incentivestandardid = item.itemValue
        }
        // 新增
        const rules = reactive({
            name: [
                { required: true, message: '请输入平台名称', trigger: 'change', },
            ],
            approvedDate: [
                { required: true, message: '请输入获批时间', trigger: 'change', },
            ],
            subsidy: [
                { required: true, message: '请输入资金补助(万元)', trigger: 'change', },
            ],
            level: [
                { required: true, message: '请输入平台级别', trigger: 'blur' },
            ],
            subject: [
                { required: true, message: '请输入平台类别', trigger: 'change', },
            ],
            approvedNumber: [
                { required: true, message: '请输入获批文件编号', trigger: 'change', },
            ],
            introduction: [
                { required: true, message: '请输入建设情况简介', trigger: 'blur' },
            ],
            incentivestandard: [
                { required: true, message: '请输入奖励标准', trigger: 'blur' },
            ],
        })

        const ruleFormRef = ref()
        const ruleFormRef1 = ref()
        const submitForm = async () => {
            ruleFormRef.value.validate(valid =>{
                if (valid){
                    emit('valueFlag2', true)
                }else{
                    emit('valueFlag2', false)
                }
            })
        }

        // 移除标签调用
        const removeTag = (value) => {
            const item = findItemNested(data.selOp, value, 'children')
            let arr = ruleForm.mainUnitName.split(',')
            let arr1 = ruleForm.mainUnitId.split(',')
            let result = arr.indexOf(item.name)
            if (result > -1) {
                arr.splice(arr.indexOf(item.name), 1)
                arr1.splice(arr1.indexOf(item.id), 1)
            }
            ruleForm.mainUnitName = arr + ''
            ruleForm.mainUnitId = arr1 + ''
        }

        function findItemById(list, id) {
            // 每次进来使用find遍历一次
            let res = list.find((item) => item.id == id);
            if (res) {
                return res;
            } else {
                for (let i = 0; i < list.length; i++) {
                if (list[i].children instanceof Array && list[i].children.length > 0) {
                    res = findItemById(list[i].children, id);
                    if (res) return res;
                }
                }
                return null;
            }
        };
        const chooseMatter = (value) => {
            let arr = [] as any
            ruleForm.mainUnitId = value.join(',')
            value.forEach(e =>{
                let o = findItemById(data.selOp,e)
                arr.push(o.name)
            })
            ruleForm.mainUnitName = arr.join(',')

            // console.log(value)
            // let arr = ruleForm.mainUnitName
            // let arr1 = ruleForm.mainUnitId
            // value.map((i) => {
            //     const item = findItemNested(selOp.value, i, 'children')

            //     let result = arr.indexOf(item.name)
            //     if (result > -1) {
            //         return;
            //     }
            //     arr = arr + ',' + item.name
            //     arr1 = arr1 + ',' + item.id
            // })
            // ruleForm.mainUnitName = arr
            // ruleForm.mainUnitId = arr1
        }


        const removeTag1 = (value) => {
            const item = findItemNested(data.selOp, value, 'children')
            let arr = ruleForm.constructionUnitId.split(',')
            let result = arr.indexOf(item.id)
            if (result > -1) {
                arr.splice(arr.indexOf(item.id), 1)
            }
            ruleForm.constructionUnitId = arr + ''
        }

        const chooseMatter1 = (value) => {
            let arr = [] as any
            ruleForm.constructionUnitId = value.join(',')
            value.forEach(e =>{
                let o = findItemById(data.selOp,e)
                arr.push(o.name)
            })
            ruleForm.constructionUnitName = arr.join(',')
            // let arr = ruleForm.constructionUnitName
            // value.map((i) => {
            //     const item = findItemNested(selOp.value, i, 'children')

            //     let result = arr.indexOf(item.id)
            //     if (result > -1) {
            //         return;
            //     }
            //     arr = arr + ',' + item.id
            // })
            // ruleForm.constructionUnitId = arr
        }

        const findItemNested = (arr, itemId, nestingKey) => (
            arr.reduce((a, item) => {
                if (a) return a;
                if (item.id === itemId) return item;
                if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
            }, null)
        );

        const personForm = reactive({
            unit: '',
            unitid: '',
            joinusernameid: '',
            joinusername: '',
            role: '',
        })

        const changeName = (item) => {
            personForm.joinusername = item.username
            personForm.joinusernameid = item.userId
        }

        const changeUnit = (item) => {
            console.log(item)
            personForm.unit = item.name
            personForm.unitid = item.id
        }

        const changeRole = (item) => {
            console.log(item)
            // personForm.roleName = item.roleName
            personForm.role = item.roleName
        }

        const addPerson = () => {
            if (personForm.joinusername) {
                let obj = {
                    unit: personForm.unit,
                    unitid: personForm.unitid,
                    joinusernameid: personForm.joinusernameid,
                    joinusername: personForm.joinusername,
                    role: personForm.role,
                }
                if (JSON.stringify(usersList.value).indexOf(JSON.stringify(obj)) == -1) {
                    usersList.value.push(obj)
                } else {
                    tips('不可添加相同成员', 'warning')
                    return;
                }
                Object.keys(personForm).forEach((key) => {
                    personForm[key] = ''
                })
                console.log(usersList)
                emit('usersChange', usersList)
            }
        }
        onMounted(() =>{
            nextTick(() =>{
             getOrgList()
            })
        })

        return {
            open,
            ruleForm,
            rules,
            ruleFormRef,
            ruleFormRef1,
            labelPosition,
            data,
            options,
            usersList,
            personForm,

            chooseMatter,
            removeTag,
            chooseMatter1,
            removeTag1,
            addPerson,

            changeName,
            changeUnit,
            changeRole,

            changeValue,
            changeValue1,
            submitForm,
            changeValue3
        }
    },
}
</script>
<style lang="scss" scoped>
.personAddBtn {
    position: absolute;
    bottom: 0;
    right: 0;
}

.demo-form-inline .el-form-item {
    width: 48%;
}

:deep(.labelHeight .el-form-item__label) {
    line-height: 20px;
}

:deep(.el-date-editor.el-input) {
    width: 100%;
}

:deep(.el-date-editor.el-input__inner) {
    width: 100%;
}

:deep(.demo-form-inline .el-select) {
    width: 100%;
    margin: 0;
}

.el-select {
    width: 100%;
    margin: 0;
}

.selectLabel {
    width: 70%;
    min-height: 40px;
    line-height: 40px;
    padding: 0 15px;
    border: 1px solid #ccc;
    border-radius: 6px;
    display: inline-block;
}

.addLabel {
    display: inline-block;
    width: 120px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    background-color: #169bd5;
    border-radius: 6px;
    color: #fff;
    margin-left: 15px;
}

.unitBox {
    width: 100%;
    margin: 30px 0;

    .title {
        padding: 15px 0;
        border-bottom: 1px solid #ccc;
    }

    .tagBox {
        line-height: 40px;
        margin-top: 15px;
        border: 1px solid #ccc;
        border-radius: 8px;
        padding: 10px 15px;
    }
}

.el-tag {
    margin-right: 10px;
}


.content-box {
    width: 250px;
    height: 33px;
    padding: 5px;
    box-sizing: border-box;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.select {
    color: #eee;
}

.align-center {
    align-items: center;
}

.space-between {
    justify-content: space-between;
}

.mt20 {
    margin-top: 20px;
}

.flex {
    display: flex;
}

.handle {
    position: absolute;
    top: 17px;
    right: 20px;
    display: flex;
    align-items: center;
}

.search-box {
    display: flex;
    justify-content: end;
    align-items: center;
    margin-bottom: 10px;
}
</style>
